package com.mianle.userapi.util;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.mianle.userapi.config.SmsConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Slf4j
public class AliyunMessageUtil {

    @Autowired
    private SmsConfig smsConfig;



    public String sendSms(Map<String, String> paramMap) throws ClientException {

        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        IClientProfile profile = DefaultProfile.getProfile(smsConfig.getRegionId(), smsConfig.getAccessKeyId(), smsConfig.getAccessKeySecret());
        DefaultProfile.addEndpoint(smsConfig.getEndpointName(), smsConfig.getRegionId(), smsConfig.getProduct(), smsConfig.getDomain());
        IAcsClient acsClient = new DefaultAcsClient(profile);

        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(paramMap.get("phoneNumber"));
        request.setSignName(smsConfig.getMsgSign());
        request.setTemplateCode(smsConfig.getTemplateCode());
        request.setTemplateParam(paramMap.get("jsonContent"));
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);

        if (sendSmsResponse != null) {
            log.info("#sendSms# sendSmsResponse:{}",sendSmsResponse.toString());
        }


        String code = sendSmsResponse.getCode();
        if(code != null && code.equals("OK")) {
            //短信发送成功
            return "success";
        }
        if (code != null && code.equals("isv.BUSINESS_LIMIT_CONTROL")){
            //业务限流 支持1条/分钟，5条/小时 ，累计10条/天
            log.info(sendSmsResponse.getMessage());
            return "发送短信太过频繁，请稍候再发！";
        }else{
            log.info(sendSmsResponse.getMessage());
            return "短信发送失败，请稍后再试！";
        }
    }
}
